package cn.zzdt4j.config.springboot.starter.refresher;

import cn.zzdt4j.threadpool.dynamic.model.config.properties.BootstrapConfigProperties;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigChangeListener;
import com.ctrip.framework.apollo.ConfigFile;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import com.ctrip.framework.apollo.model.ConfigChange;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import java.util.HashMap;
import java.util.Map;

/**
 * Apollo refresher handler
 *
 * @author by <a href="mailto:ligang941012@gmail.com">gang.Li</a>
 * @since 2024/5/13 1:46
 */
@Slf4j
public class ApolloRefresherHandler extends AbstractConfigThreadPoolDynamicRefresh {

    private static final String APOLLO_PROPERTY = "${spring.dynamic.thread-pool.apollo.namespace:application}";

    @Value(APOLLO_PROPERTY)
    private String namespace;

    @Override
    public void registerListener() {
        String[] apolloNamespaces = this.namespace.split(",");
        this.namespace = apolloNamespaces[0];
        BootstrapConfigProperties actualBootstrapConfigProperties = (BootstrapConfigProperties) bootstrapConfigProperties;
        Config config = ConfigService.getConfig(String.format("%s.%s", namespace, actualBootstrapConfigProperties.getConfigFileType().getValue()));
        ConfigChangeListener configChangeListener = configChangeEvent -> {
            String namespace = this.namespace.replaceAll("." + actualBootstrapConfigProperties.getConfigFileType().getValue(), "");
            final ConfigFileFormat configFileFormat = ConfigFileFormat.fromString(actualBootstrapConfigProperties.getConfigFileType().getValue());
            final ConfigFile configFile = ConfigService.getConfigFile(namespace, configFileFormat);
            Map<String, Object> newValueChangeMap = new HashMap<>();
            configChangeEvent.changedKeys().stream().filter(each -> each.contains(BootstrapConfigProperties.PREFIX))
                    .forEach(each -> {
                        final ConfigChange change = configChangeEvent.getChange(each);
                        final String newValue = change.getNewValue();
                        newValueChangeMap.put(each, newValue);
                    });
            dynamicRefresh(configFile.getContent(), newValueChangeMap);
        };
        config.addChangeListener(configChangeListener);
        log.info("Dynamic thread pool refresher, add apollo listener success. namespace: {}", namespace);
    }
}
